import numpy as np
import pylab as pl


def phi_k(x, k):
    y = x ** k
    return y


def squar_least(x, y, w, n):
    G = np.zeros((n + 1, n + 1))
    d = np.zeros((n + 1))
    for i in range(n + 1):
        for j in range(n + 1):
            G[i, j] = sum((w * phi_k(x, i)) * phi_k(x, j))  #算n  x的和 x^2的和

    for i in range(n + 1):
        d[i] = sum((w * phi_k(x, i)) * y)  #算y的和  xy的和

    a = np.dot(np.linalg.inv(G), d)#解方程
    return a


x = np.array([1, 4, 9, 16, 25, 36, 49, 64, 81])
y = np.array([1, 2, 3.1, 3.95, 5.01, 6, 6.97, 8, 9.02])
w = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1])

a = squar_least(x, y, w, 2)#2指的是2阶
yuce_y = a[0] * 1 + a[1] * 0.6 + a[2] * 0.6 * 0.6
print(yuce_y)

xxx = [];
yyy = []
for i in range(0, 11):
    xxx.append(i / 10)
    yyy.append(a[0] * 1 + a[1] * i / 10 + a[2] * i / 10 * i / 10)
pl.scatter(x, y)
pl.plot(xxx, yyy)

a = squar_least(x, y, w, 1)#1指的是1阶
yuce_y = a[0] * 1 + a[1] * 0.6
print(yuce_y)

xxx = [];
yyy = []
for i in range(0, 11):
    xxx.append(i / 10)
    yyy.append(a[0] * 1 + a[1] * i / 10 )
pl.scatter(x, y)
pl.plot(xxx, yyy)
